package com.framework.service.impl;

import cn.dev33.satoken.util.SaResult;
import com.framework.entity.Menu;
import com.framework.entity.RoleMenu;
import com.framework.repository.RoleMenuRepository;
import com.framework.service.RoleMenuService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;
import java.util.List;
import java.util.UUID;

/**
 * @Description: 角色-权限服务接口服务接口实现
 * @Author: JamesYao
 * @DateTime: 2024/2/19 17:20
 */

@Service
@RequiredArgsConstructor
@Transactional
public class RoleMenuServiceImpl implements RoleMenuService {

    private final RoleMenuRepository roleMenuRepository;

    @PersistenceContext
    private EntityManager entityManager;

    /**
     * 根据角色ID查找菜单列表
     * 使用Hibernate Criteria查询方式查找菜单列表 SELECT m FROM Menu m WHERE m.id IN (SELECT rm.menuId FROM RoleMenu rm WHERE rm.roleId = :roleId)
     * @param roleId 角色ID
     * @return 菜单列表
     */
    @Override
    public List<Menu> findMenusByRoleId(UUID roleId){
        String jpql = "select m from Menu m JOIN RoleMenu rm ON m.id = rm.menuId WHERE rm.roleId = :roleId";
        return this.entityManager.createQuery(jpql, Menu.class)
                .setParameter("roleId", roleId)
                .getResultList();
    }


    @Override
    public SaResult saveRoleMenu(RoleMenu roleMenu) {
        roleMenuRepository.save(roleMenu);
        return SaResult.ok();
    }
}
